<template>
    <div class="main order-list">
        <!--<div class="tool-bar">
            <div class="form-item">
                <el-date-picker
                    v-model="syncTime"
                    type="datetime"
                    value-format="yyyy/MM/dd HH:mm:ss"
                    placeholder="选择同步起始时间">
                </el-date-picker>
                <el-button type="danger" v-loading.fullscreen.lock="syncLoading" element-loading-background="rgba(0, 0, 0, 0.7)" element-loading-text="订单同步中,请勿关闭或者刷新页面" @click="syncAllOrder">同步</el-button>
            </div>
        </div>-->
      <section>
        <div class="search-block">
          <el-row :gutter="30">
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">订单号</span>
                <el-input @keyup.enter.native="search" v-model="params.orderNo"></el-input>
            </div>
            <!--<div class="form-item">
                <span class="item-title">E3单号</span>
                <el-input @keyup.enter.native="search" v-model="params.e3OrderNo"></el-input>
            </div>-->
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">下单人</span>
                <el-input @keyup.enter.native="search" v-model="params.realName"></el-input>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">下单人手机号</span>
                <el-input @keyup.enter.native="search" v-model="params.userMobile"></el-input>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">收货人</span>
                <el-input @keyup.enter.native="search" v-model="params.consignee"></el-input>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">收货人手机号</span>
                <el-input @keyup.enter.native="search" v-model="params.mobile"></el-input>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">订单状态</span>
                <el-select v-model="params.status">
                    <el-option label="所有" value=""></el-option>
                    <el-option v-for="(name, val) in states" :key="val" :label="name" :value="val"></el-option>
                </el-select>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">售后状态</span>
                <el-select v-model="params.statusInfo">
                    <el-option label="所有" value=""></el-option>
                    <el-option v-for="(name, val) in afterSaleStates" :key="val" :label="name" :value="val"></el-option>
                </el-select>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">订单类别</span>
                <el-select v-model="params.type" @change="showExport(params.type)">
                    <el-option label="所有" value=""></el-option>
                    <el-option v-for="(name, val) in types" :key="val" :label="name" :value="val"></el-option>
                </el-select>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">时间</span>
                <el-date-picker
                    v-model="timeRange"
                    type="daterange"
                    range-separator="~"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <div class="form-item">
                <span class="item-title">发票状态</span>
                <el-select v-model="params.electronicInvoiceStatus">
                  <el-option label="全部" value=""></el-option>
                  <el-option :label="item.label" :value="item.value" v-for="(item, index) in invoiceStatusArr" :key="index"></el-option>
                </el-select>
            </div>
            </el-col>
            <el-col
              :sm="24"
              :md="12"
              :lg="8"
              :xl="6"
            >
            <!--<div class="form-item">
                <span class="item-title">供应商名称</span>
                <el-input @keyup.enter.native="search" v-model="params.merchantName"></el-input>
            </div>-->
            <div class="form-item col-1">
                <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
            </div>
            </el-col>
          </el-row>
        </div>
        <el-button style=" margin-bottom: 10px" type="success" :loading="downLoadStatus" v-if="rightsButtons['export']" >
          <span @click="download">导出{{types[params.type] || '所有'}}</span>
        </el-button>
        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="订单号">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="scope.row.orderNo"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="收货人">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="scope.row.consignee"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="收货地址">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="`${scope.row.country} ${scope.row.province} ${scope.row.city} ${scope.row.address}`"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="付款金额">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p>{{scope.row.realPayPrice}}</p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="商品总金额" prop="productPayPrice"></el-table-column>
            <el-table-column align="center" label="邮费" prop="postage"></el-table-column>
            <el-table-column align="center" label="状态" width="80">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="states[scope.row.status + '']"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="订单类别" width="120">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-if="scope.row.type === 11">
                          <span v-if="scope.row.activityId&&!scope.row.boxOrderType">箱起礼包</span>
                          <span v-else-if="scope.row.boxOrderType===1">箱起云仓单</span>
                          <span v-else-if="scope.row.boxOrderType===2">箱起提货单</span>
                          <span v-else-if="scope.row.boxOrderType===3">箱起特权包</span>
                          <span v-else>箱起零售</span>
                        </p>
                        <p v-else v-text="types[scope.row.type + ''] || scope.row.type"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="售后状态" width="100">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="afterSaleStates[scope.row.statusInfo + '']"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="160">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="formatDate(scope.row.createdAt, 'YYYY-MM-DD HH:mm:ss')"></p>
                    </div>
                </template>
            </el-table-column>
            <!--<el-table-column align="center" label="E3单号">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="scope.row.e3OrderNo"></p>
                    </div>
                </template>
            </el-table-column>-->
            <el-table-column align="center" label="最后同步时间">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="formatDate(scope.row.lastSyncTime, 'YYYY-MM-DD HH:mm:ss')"></p>
                    </div>
                </template>
            </el-table-column>

            <el-table-column align="center" label="发票状态">
              <template slot-scope="scope">{{scope.row.electronicInvoiceStatus}}</template>
            </el-table-column>
            <el-table-column align="center" label="已开票金额" prop="alreadyAmount"></el-table-column>
             <el-table-column align="center" label="未开票金额" prop="allowAmount"></el-table-column>
            <el-table-column align="center" label="操作" width="200" >
                <template slot-scope="scope">
                    <router-link :to="{path: 'detail', query: {id: scope.row.orderId ,type: scope.row.type}}" v-if="rightsButtons['detail']">
                        <el-button type="primary" size="mini">查看</el-button>
                    </router-link>
                    <el-button  type="primary" size="mini" @click="lookTax(scope.row)" v-if="rightsButtons['openTax'] && (scope.row.electronicInvoiceStatus === '开票成功' || scope.row.electronicInvoiceStatus === '部分成功' || scope.row.electronicInvoiceStatus === '红冲成功')">查看发票</el-button>
                    <el-button  type="primary" size="mini" @click="applyTax(scope.row)" v-if="rightsButtons['applyTax'] && scope.row.status === 4 && scope.row.electronicInvoiceStatus === '未开票'" >申请发票</el-button>
                    <!--<el-button type="danger" size="mini" @click="syncOrder(scope.row.orderNo)">同步</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="total > 0">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
        </div>
      </section>
        <el-dialog title="查看发票" :visible.sync="dialogVisibleTax">
           <div class="tax-pic">
              <el-table :data="taxTick"  border highlight-current-row>
                <el-table-column align="center" label="类型">
                  <template slot-scope="scope">
                      <span v-if="scope.row.bluePdfPath">蓝票：{{scope.row.blueInvoiceNo}}</span>
                      <span v-if="scope.row.redPdfPath">红票：{{scope.row.redInvoiceNo}}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" v-if="scope.row.bluePdfPath" @click="lookTaxPic(scope.row, 1)">查看蓝票</el-button>
                    <el-button type="primary" size="mini" v-if="scope.row.redPdfPath" @click="lookTaxPic(scope.row, 2)">查看红票</el-button>
                  </template>
                </el-table-column>
              </el-table>
           </div>
        </el-dialog>
        <el-dialog title="查看发票" :visible.sync="showTaxPic">
           <div class="tax-pic">
             <img :src="item" alt="" v-for="(item, index) in taxPicList" :key="index" style="width: 100%"/>
           </div>
        </el-dialog>
    </div>
</template>

<script>
  import moment from 'moment'
    export default {
        name: 'order',
        data() {
            return {
                showBtn: false,
                list: [],
                params: {
                    orderNo: '',
                    e3OrderNo: '',
                    realName: '',
                    userMobile: '',
                    consignee: '',
                    mobile: '',
                    status: '',
                    statusInfo: '',
                    type: '',
                    electronicInvoiceStatus: ''
                },
                timeRange: [],
                query: {},
                page: 1,
                pageSize: 20,
                total: 0,
                syncTime: '',
                syncLoading: false,
                downLoadStatus: false,
                // 状态
                states: {
                    '1': '待付款',
                    '2': '待发货',
                    '3': '待收货',
                    '4': '已收货',
                    '5': '已取消',
                    '6': '付款异常',
                    '7': '超时取消',
                    '8': '已退款',
                    '10': '待发货',
                    '11': '待成团',
                },
                // 售后状态
                afterSaleStates: {
                    '1': '申请中',
                    '2': '审核通过',
                    '3': '审核不通过',
                    '4': 'E3处理中',
                    '5': 'E3处理成功',
                    '6': 'E3处理失败',
                    '7': '退货入库成功',
                    '8': '退货入库失败',
                    '9': '审核物流状态中',
                    '10': '审核物流状态成功',
                    '11': '审核物流状态失败',
                    '12': '退款处理中',
                    '13': '退款成功',
                    '14': '退款失败',
                },
                // 类型
                types: { // 订单类别
                  '1': '普通',
                  '2': '会员礼包',
                  '3': '会员组合礼包',
                  '4': '大区礼包',
                  '9': '城市合伙人',
                  // '11': '箱起',
                  '13': '新人礼包',
                  '14': '门店大区礼包',
                  '15': '保证金礼包',
                  '18': '红石榴箱起',
                  '19': '3亿红包',
                  '22': '38元礼包',
                  '24': '满减',
                  '25': '拼团订单',
                  '101': '会员专享订单',
                  '151': '签到打卡赠品面膜',
                  '152': '签到券订单',
                  '153': '签到赠品订单',
                  '202': '站外16元面膜',
                  '211': '网红面膜赠品',
                  '251': '网红面膜箱起',
                  '1001': 'M件N元',
                  '1101': '箱起礼包',
                  '1102': '箱起零售',
                  '260': '29.9元礼包',
                  '1103': '箱起云仓单',
                  '1104': '箱起提货单',
                  '1105': '箱起特权包',
                  '301': '红药房-普通商品',
                  '302': '红药房-团购商品',
                  '303': '红药房-店员商品',
                  '304': '红药房-店长商品',
                  '305': '红药房-县代商品',
                  '306': '红药房-市代商品',
                  '30': '免费领',
                  '31': '低价购',
                },
                listLoading: false,
                btnDisabled: false,
                invoiceStatusArr: [
                  // {label: '新建', value: 'INVOICE_APPLY'},
                  // {label: '部分成功', value: 'INVOICE_PARTIAL_SUCCESS'},
                  // {label: '开票成功', value: 'INVOICE_SUCCESS'},
                  // {label: '待红冲', value: 'INVOICE_WAIT_APPLY'},
                  //  {label: '待开票 ', value: 'INVOICE_WAIT_MARK'},
                  // {label: '红冲成功', value: 'INVOICE_WASH_SUCCESS'},
                  {label: '新建', value: '新建'},
                  {label: '部分成功', value: '部分成功'},
                  {label: '未开票', value: '未开票'},
                  {label: '开票成功', value: '开票成功'},
                  {label: '待红冲', value: '待红冲'},
                  {label: '待开票 ', value: '待开票'},
                  {label: '红冲成功', value: '红冲成功'},
                ],
                dialogVisibleTax: false, // 发票
                // dialogVisibleTaxOne: false,
               taxTick: [],
               taxPicList: [], // 发票列表
               showTaxPic: false
            }
        },
        created() {
            this.getList();
        },
        methods: {
            showExport(val) {
              if(val === '1101' || val === '1102'){
                this.showBtn = true
              } else {
                this.showBtn = false
              }
            },
            download(){
                this.downLoadStatus = true
                this.page = 1;
                let [start, end] = ['', ''];
                if(this.timeRange.length === 0){
                    this.$message({
                    type: 'error',
                    message: '请选择导出时间！'
                    })
                    this.downLoadStatus = false
                    return
                }
                if (this.timeRange && this.timeRange.length > 0) {
                    start = this.formatDate(this.timeRange[0]);
                    end = this.formatDate(this.timeRange[1]);
                }
                const monthOver = (this.timeRange[1] - this.timeRange[0]) / (1000 * 60 * 60 * 24) + 1
                if (monthOver > 31) {
                    this.$message({
                    type: 'error',
                    message: '订单数据导出最长时间不能超过1个月！'
                    })
                    this.downLoadStatus = false
                    return
                }
                const queryCon = {
                    ...this.params,
                    beginTime: start,
                    endTime: end
                }
                this.request({
                    url: '/bsnl-order/order/export',
                    method: 'get',
                    params: {
                    // offset: this.page - 1,
                    offset: this.page,
                    limit: this.pageSize,
                    ...queryCon
                    },
                    responseType: 'blob'
                }).then(res => {
                    let date = moment().format('YYYYMMDD/HHmmss').replace(/\//g, '_');
                    let filename = (this.types[this.params.type] || '所有')+`${date}.xlsx`;
                    this.downloadFile(res, filename);
                    this.downLoadStatus = false
                }).catch(err => {
                    console.log(err);
                    this.downLoadStatus = false
                })
            },

            // 获取列表
            getList() {
                this.listLoading = true;
                this.request({
                    url: '/bsnl-order/order/list',
                    method: 'get',
                    params: {
                        // offset: this.page - 1,
                        offset: this.page,
                        limit: this.pageSize,
                        ...this.query
                    }
                }).then(({rows, total}) => {
                    this.list = rows;
                    this.total = total;
                    this.listLoading = false;
                }).catch(err => {
                    console.log(err);
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
            },
            // 删除
            del(item) {
                this.$confirm(`确定要删除 ${item.name} 吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.request({
                        url: '/bsnl-product/tag/delete',
                        method: 'post',
                        data: {
                            id: item.id,
                            deleteFlag: 0
                        }
                    }).then(() => {
                        if (this.page > 1 && this.list.length === 1) {
                            this.page--;
                        }
                        this.getList();
                        this.$message.success('删除成功');
                    }).catch(err => {
                        console.log(err);
                        this.list = [];
                        this.total = 0;
                        this.listLoading = false;
                    });
                }).catch(err => {
                    console.log(err);
                });
            },
            // 搜索
            search() {
                this.page = 1;
                let [start, end] = ['', ''];
                if (this.timeRange && this.timeRange.length > 0) {
                    start = this.formatDate(this.timeRange[0]);
                    end = this.formatDate(this.timeRange[1]);
                }
                this.query = {
                    ...this.params,
                    beginTime: start,
                    endTime: end
                };
                this.getList();
            },
            // 重置
            reset() {
                this.params = {
                    orderNo: '',
                    order: '',
                    realName: '',
                    userMobile: '',
                    consignee: '',
                    mobile: '',
                    status: '',
                    statusInfo: '',
                    type: '',
                };
                this.showExport(this.params.type)
                this.timeRange = [];
                this.search();
            },
            // 切换分页
            handleCurrentChange(page) {
                this.page = page;
                this.getList();
            },
            // 同步所有订单
            syncAllOrder() {
                this.$confirm('确认进行订单同步?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.syncLoading = true;
                    this.request({
                        url: '/bsnl-erp-api/orderInfoSyn/synOrderFromApp',
                        method: 'get',
                        params: {
                            synBeginTime: this.syncTime
                        }
                    }).then((response) => {
                        console.log(response);
                        this.syncLoading = false;
                        this.$message.success('订单同步成功');
                        this.getList();
                    }).catch(err => {
                        console.log(err);
                        this.syncLoading = false;
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消订单同步'
                    });
                });
            },
            // 同步单个订单
            syncOrder(orderNo) {
                this.$confirm('确认进行订单同步?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.syncLoading = true;
                    this.request({
                        url: '/bsnl-erp-api/orderInfoSyn/synSingleOrderFromApp/'+orderNo,
                        method: 'get'
                    }).then((response) => {
                        console.log(response);
                        this.syncLoading = false;
                        this.$message.success('订单同步成功');
                        this.getList();
                    }).catch(err => {
                        console.log(err);
                        this.syncLoading = false;
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消订单同步'
                    });
                });
            },
            // 查看发票
            lookTax(item){
              this.taxTick = []
              this.request({
                url: '/invoice-web-manage/invoice/mark/order/'+item.orderNo,
                method: 'get',
                params: {
                  orderNo: item.orderNo
                }
              }).then((res) => {
                if (res.code === 200) {
                  res.data.forEach(i => {
                    if (i.bluePdfPath || i.redPdfPath){
                      this.taxTick.push({
                        blueInvoiceNo: i.blueInvoiceNo,
                        bluePdfPath: i.bluePdfPath,
                        redInvoiceNo: i.redInvoiceNo,
                        redPdfPath: i.redPdfPath
                      })
                    }
                  })
                  this.dialogVisibleTax = true
                }
              }).catch(err => {
                  console.log(err);
              });
            },

           lookTaxPic(info, index) {
              this.taxPicList = []
              if (index === 1) {
                if (info.bluePdfPath) {
                  this.taxPicList = info.bluePdfPath.split(',')
                }
              } else if (index === 2) {
                 if (info.redPdfPath) {
                  this.taxPicList = info.redPdfPath.split(',')
                }
              }
              this.showTaxPic = true

            },
            // 申请发票
            applyTax(item) {
              this.$router.push({
                path: '/order/invoice',
                query: {
                  orderNo: item.orderNo
                }
              })
            },
            // 发票状态
            invoiceStatusTxt(val) {
              const index = this.invoiceStatusArr.findIndex(i => i.value === val.electronicInvoiceStatus)
              if (index > -1){
                return this.invoiceStatusArr[index].label
              }
              return ''
            }
        }
    }
</script>
<style scoped lang="scss">
.tax-list {
  img {
    width: 200px;
    height: 100px;
    vertical-align: middle;
  }
  .down-btn {
    vertical-align: middle;
    margin-left:20px;
  }
}
 .tax-pic {
    img {
      width:100%;
    }
  }
</style>
